package com.itany.book.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.exception.RequestParamsException;
import com.itany.exception.RoleExistsExceptions;
import com.itany.exception.UsingRoleException;
import com.itany.mapper.ManagerUserRoleMapper;
import com.itany.mapper.RoleMapper;
import com.itany.mapper.RolePermissionMapper;
import com.itany.pojo.Permission;
import com.itany.pojo.Role;
import com.itany.service.RoleService;
import com.itany.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class RoleServiceImpl implements RoleService {


    @Autowired
    RoleMapper roleMapper;

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    ManagerUserRoleMapper managerUserRoleMapper;


    /**
     * 添加角色
     *
     * @param name        角色名称
     * @param permissions 角色权限
     */
    @Override
    public void addRole(String name, Integer[] permissions) throws RequestParamsException, RoleExistsExceptions {
        if(StrUtil.isBlankIfStr(name)||permissions.length == 0){
            throw new RequestParamsException("请求参数缺失");
        }
        Role role = roleMapper.selectByName(name);
        if(role != null){
            throw new RoleExistsExceptions("当前角色名已存在");
        }
         role = new Role();
        role.setName(name);
        roleMapper.insertRole(role);
        Integer roleId = role.getId();
        for (Integer permissionId:permissions) {
            rolePermissionMapper.insertRolePermission(roleId,permissionId);
        }

    }


    /**
     * 分页查找所有角色
     * @param page 页数
     * @param rows 每页数据条数
     * @return
     * @throws RequestParamsException
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public PageInfo<Role> findAll(Integer page, Integer rows,String rolenameKey) throws RequestParamsException {
        PageHelper.startPage(page, rows);
        List<Role> list;
        list = roleMapper.selectAll(StringUtils.escapeStr(rolenameKey));
        for (Role role:list) {
            List<Permission> permissions = rolePermissionMapper.selectByRoleId(role.getId());
            role.setPermissions(permissions);
        }
        return new PageInfo<>(list);
    }

    /**
     * 不分页查找所有角色
     *
     * @return
     */
    @Override
    public List<Role> findAllNoPages() {
        return roleMapper.selectAll(null);
    }

    /**
     * 修改角色信息
     *
     * @param id          角色id
     * @param name        角色名
     * @param permissions 角色权限
     * @return
     */
    @Override
    public void modifyRole(String id, String name, Integer[] permissions) throws RequestParamsException, RoleExistsExceptions {
        if(StrUtil.isBlankIfStr(id)){
            throw new RequestParamsException("请求参数缺失");
        }
        Integer idInt;
        try {
            idInt = Integer.parseInt(id);
        } catch (NumberFormatException e) {
            throw new RequestParamsException("请求参数格式错误");
        }
        if(!StrUtil.isBlankIfStr(name)){
            Role role = roleMapper.selectByName(name);
            if(role!=null&&role.getId()!=idInt){
                throw new RoleExistsExceptions("当前角色名已经存在");
            }
            roleMapper.updateRole(idInt,name);
        }
        if(permissions.length != 0){
            rolePermissionMapper.deleteByRoleId(idInt);
            for (Integer permissionId:permissions) {
                rolePermissionMapper.insertRolePermission(idInt,permissionId);
            }
        }
    }

    /**
     * 根据id删除角色
     *
     * @param id
     */
    @Override
    public void removeRole(String id) throws RequestParamsException, UsingRoleException {
        if(StrUtil.isBlankIfStr(id)){
            throw new RequestParamsException("请求参数缺失");
        }
        Integer idInt;
        try {
            idInt = Integer.parseInt(id);
        } catch (NumberFormatException e) {
            throw new RequestParamsException("请求参数格式错误");
        }
        //查找待删除的角色是否被管理员使用，如果true，不能删除
        List<Role> roles = managerUserRoleMapper.selectByRoleId(idInt);
        if(!roles.isEmpty()){
            throw new UsingRoleException("该角色正在使用，不能删除");
        }
        rolePermissionMapper.deleteByRoleId(idInt);
        roleMapper.deleteById(idInt);
    }
}
